package asia.lxq.cic.service;

import asia.lxq.cic.aop.NeedAop;
import asia.lxq.cic.config.GlobalConfig;
import asia.lxq.cic.dao.AreaMapper;
import asia.lxq.cic.dao.GroupMapper;
import asia.lxq.cic.dao.UserMapper;
import asia.lxq.cic.entity.Result;
import asia.lxq.cic.entity.User;
import asia.lxq.cic.util.BCryptPasswordUtil;
import asia.lxq.cic.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AreaMapper areaMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    GroupMapper groupMapper;

    public Result<Object> userList(int page, int pageSize) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+authentication.getPrincipal());
        user.query(areaMapper);
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.like("belong","%,%,"+user.getCollegeId()+",%");
        Page<User> userPage=userMapper.selectPage(new Page<>(page,pageSize),userQueryWrapper);
        List<User> userList = userPage.getRecords();
        userList.forEach(userItem->{
            userItem.setGroup(groupMapper.selectById(Integer.parseInt(userItem.getBelong().split(",")[3])));
            userItem.query(areaMapper);
        });
        Map<String,Object> resultData=new HashMap<>();
        resultData.put("data",userList);
        resultData.put("total",userPage.getTotal());
        resultData.put("current",userPage.getCurrent());
        resultData.put("pages",userPage.getPages());
        return Result.success(resultData);
    }

    public Result<Object> addUser(List<User> userList){
        userList.forEach(user -> {
            user.setUserId(0);
            user.setPassword(BCryptPasswordUtil.BCryptPasswordEncoder(user.getPassword()));
            user.setCreatedDate(null);
            String[] split = user.getBelong().split(",");
            for (int i = 0; i < split.length; i++) {
                if (split[i].equals("undefined")) {
                    split[i]="0";
                }
            }
            user.setBelong(split[0]+','+split[1]+','+split[2]+','+split[3]);
            userMapper.insert(user);
        });
        return Result.success();
    }

//    public Result<Object> getAllArea(){
//        return Result.success(areaMapper.selectProvince());
//    }


    public Result<Object> deleteUserList(int[] userIds){
        for (int userId : userIds) {
            userMapper.deleteById(userId);
            redisUtil.del(GlobalConfig.PRE_USERINFO_REDIS+userId);
        }
        return Result.success();
    }

    @NeedAop
    public Result<Object> updateUser(User user,Authentication authentication){
        User admin = userMapper.selectById(Integer.parseInt(authentication.getPrincipal() + ""));
        String[] adminBelong = admin.getBelong().split(",");
        adminBelong[3]=user.getGroupId()+"";
        user.setBelong(String.format("%s,%s,%s,%s",adminBelong[0],adminBelong[1],adminBelong[2],adminBelong[3]));
        userMapper.updateById(user);
        return Result.success(user);
    }
}
